package com.example.filesplit.demos.web;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MergeController {
    @PostMapping("/merge")
    public ResponseEntity<byte[]> mergeWordFile(@RequestParam("templeteFile") MultipartFile templeteFile,
                                                @RequestParam("unitFile") List<MultipartFile> unitFileList,
                                                @RequestParam("keyIndex") Integer key,
                                                @RequestParam("mergeIndex") List<Integer> mergeIndexList) {
        try {
            // 读取模板文件
            XWPFDocument templateDoc = new XWPFDocument(templeteFile.getInputStream());
            XWPFTable templateTable = templateDoc.getTableArray(0); // 假设模板中有一个表格

            // 创建一个 Map 用于存储模板中的 key 列和对应的行
            Map<String, XWPFTableRow> templateRowMap = new HashMap<>();
            for (int i = 1; i < templateTable.getRows().size(); i++) {
                XWPFTableRow row = templateTable.getRow(i);
                // 检查 key 列的单元格是否存在
                if (row.getCell(key) != null) {
                    String keyValue = row.getCell(key).getText();
                    templateRowMap.put(keyValue, row);
                }
            }

            // 遍历每个单元文件
            for (MultipartFile unitFile : unitFileList) {
                String originalFilename = unitFile.getOriginalFilename();
                //Pattern pattern = Pattern.compile("\\((.*?)\\)");
                Pattern pattern = Pattern.compile("[\\(（](.*?)[\\)）]");
                Matcher matcher = pattern.matcher(originalFilename);

                // 查找匹配项
                if (matcher.find()) { // 确保找到匹配项
                    originalFilename = "【" + matcher.group(1) + "】"; // 只有在找到匹配项后才执行
                } else {
                    originalFilename = ""; // 如果没有找到匹配项，可以设置为默认值或空字符串
                }
                XWPFDocument unitDoc = new XWPFDocument(unitFile.getInputStream());
                XWPFTable unitTable = unitDoc.getTableArray(0); // 假设单元文件中有一个表格

                // 遍历单元文件的表格行
                for (int i = 1; i < unitTable.getRows().size(); i++) {
                    XWPFTableRow unitRow = unitTable.getRow(i);
                    // 检查 key 列的单元格是否存在
                    if (unitRow.getCell(key) != null) {
                        String unitKeyValue = unitRow.getCell(key).getText();

                        // 检查 key 列是否匹配
                        if (templateRowMap.containsKey(unitKeyValue)) {
                            XWPFTableRow templateRow = templateRowMap.get(unitKeyValue);
                            // 将单元文件的 mergeIndexList 列的数据合并到模板的相应列中
                            for (int mergeIndex : mergeIndexList) {
                                // 检查 mergeIndex 列的单元格是否存在
                                if (unitRow.getCell(mergeIndex) != null) {
                                    String valueToMerge = unitRow.getCell(mergeIndex).getText();
                                    XWPFTableCell cell = templateRow.getCell(mergeIndex);
                                    if (cell != null) {
                                        cell.setText(valueToMerge);
                                    }
                                }
                            }
                        }
                    }
                }

            }

            // 保存合并后的文档
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            templateDoc.write(outputStream);
            byte[] documentBytes = outputStream.toByteArray();

            // 设置响应头，返回合并后的文档
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
            String encodedFilename = URLEncoder.encode(templeteFile.getOriginalFilename(), StandardCharsets.UTF_8.toString());
            headers.setContentDispositionFormData("attachment", encodedFilename);
            headers.setContentLength(documentBytes.length);

            return new ResponseEntity<>(documentBytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            throw new RuntimeException("Error processing files: " + e.getMessage(), e);
        }
    }
}
